package self.wargon.springcloudstu.gateway.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoggingFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, org.springframework.cloud.gateway.filter.GatewayFilterChain chain) {
        long startTime = System.currentTimeMillis();

        String path = exchange.getRequest().getPath().toString();
        log.info("➡️ 请求路径: {}", path);

        exchange.getRequest().getHeaders().forEach((key, value) -> {
            log.info("📨 Header: {} = {}", key, value);
        });

        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    long duration = System.currentTimeMillis() - startTime;
                    log.info("✅ 响应完成，耗时: {} ms", duration);
                })
        );
    }

    @Override
    public int getOrder() {
        return -1; // 优先级高于默认过滤器
    }
}
